package dragon.tagext.easyui;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import dragon.core.exception.ExceptionHandler;
import dragon.core.system.po.SysUser;
import dragon.core.util.GlobalParameter;
import dragon.core.util.StringUtils;
import dragon.model.bizObject.BizObject;
import dragon.model.bizObject.BizProcess;
import dragon.model.permission.PermissionCheck;

@SuppressWarnings("serial")
public class Tree extends BodyTagSupport {

	private String js;
	private String html;

	@Override
	public int doStartTag() throws JspException {
		//获取业务模型
		BizObject bizObject = (BizObject) pageContext.getRequest().getAttribute("bizObject");
		//获取当前用户
		SysUser user = (SysUser) pageContext.getSession().getAttribute(GlobalParameter.User);
		//是否有弹窗URL链接
		boolean hasOpenUrl = false;
		
		if (bizObject != null) {
			StringBuffer sb_js = new StringBuffer();
			StringBuffer sb_html = new StringBuffer();
			//js部分开始
			
			//声明 暂存所有从表列表参数 数组
			sb_js.append("var args = new Array(").append(bizObject.getDependby().size()).append(");\n");
			//声明树跟节点
			sb_js.append("var treeRoot;\n");
			//初始化函数开始
			sb_js.append("$(function() {\n");
			//初始化Tree
			sb_js.append("\t$('#mytree').tree({\n");
			//声明JSON数据格式
			sb_js.append("\t\tdata: [{ id : 'null', text: 'ROOT', state: 'closed' }],\n");
			//是否支持节点移动
			if (bizObject.getDnd() == 1) {
				sb_js.append("\t\tdnd : true,\n");
				sb_js.append("\t\tonDrop : function(target, source, point){\n");
				//是否存在预定义方法
				if (!StringUtils.isEmpty(bizObject.getDndAction())) {
					sb_js.append("\t\t\ttop.showConfirm('操作确认','确定移动节点？',function(){\n\t\t\t\t$.post('").append(bizObject.getDndAction()).append("',{\n\t\t\t\t\tid : source.id,\n\t\t\t\t\ttarget : $(target).attr('node-id')\n\t\t\t\t},function(data){\n\t\t\t\t\tif(data.result !=undefined && data.result == true){\n\t\t\t\t\t\ttop.showMsg('','节点移动成功！',false);\n\t\t\t\t\t}\n\t\t\t\t\tif(data.MESSAGE_ERROR != undefined && data.MESSAGE_ERROR != ''){\n\t\t\t\t\t\ttop.showMsg('错误', data.MESSAGE_ERROR, true,'error');\n\t\t\t\t\t}else if(data.MESSAGE_WARNING != undefined && data.MESSAGE_WARNING != ''){\n\t\t\t\t\t\ttop.showMsg('警告', data.MESSAGE_WARNING, true,'warning');\n\t\t\t\t\t}else if(data.MESSAGE_INFO != undefined && data.MESSAGE_INFO != ''){\n\t\t\t\t\t\ttop.showMsg('', data.MESSAGE_INFO, false);\n\t\t\t\t\t}\n\t\t\t\t},'json')\n\t\t\t},function(){\n\t\t\t\tvar node = $('#mytree').tree('find', source.attributes.PID);\n\t\t\t\t$('#mytree').tree('reload', target);\n\t\t\t\t$('#mytree').tree('reload', node.target);\n\t\t\t\t$('#mytree').tree('expand', node.target);\n\t\t\t})\n");
				} else {
					//执行用户自己的方法
					sb_js.append("\t\t\tif($.isFunction(window.dnd))").append("{\n\t\t\t\tdnd(target, source, point);\n\t\t\t}\n");
				}
				sb_js.append("\t\t},\n");
			}
			sb_js.append("\t\tonClick : function(node) {\n\t\t\tload(node);\n\t\t},\n");
			sb_js.append("\t\tonBeforeLoad : function(node, param) {\n");
			sb_js.append("\t\t\tif (node != null) {\n");
			sb_js.append("\t\t\t\t$('#mytree').tree('options').url = 'dragon/model/action/BizObjectHandler/loadData.ejw?tree=true&bizCode=").append(bizObject.getCode()).append("&").append(bizObject.getDependParamK().toUpperCase()).append("=' + node.id;\n");
			sb_js.append("\t\t\t}\n");
			sb_js.append("\t\t\treturn true;\n");
			sb_js.append("\t\t}\n");
			sb_js.append("\t});\n");

			sb_js.append("\ttreeRoot = $('#mytree').tree('getRoot');\n");
			sb_js.append("\t$('#mytree').tree('expand',treeRoot.target);\n");

			for (int i = 0; i < bizObject.getDependby().size(); i++) {
				String dependParam = "";
				BizObject dpb = bizObject.getDependby().get(i);
				if (dpb.getDependParam() != null) {
					String p = pageContext.getRequest().getParameter(dpb.getDependParamV().toUpperCase());
					dependParam = "&" + dpb.getDependParamV().toUpperCase() + "=" + p;
				}
				sb_js.append("\targs[" + i + "] = 'bizCode=" + dpb.getCode() + "&list=true" + dependParam + "';\n");
			}

			sb_js.append("\t$('#tabs').tabs({\n");
			sb_js.append("\t\tonSelect : function(title,index){\n");
			sb_js.append("\t\t\tvar tab = $('#tabs').tabs('getSelected');\n");
			sb_js.append("\t\t\tvar tabIframe = tab.find('iframe');\n");
			sb_js.append("\t\t\tvar src = '';\n");
			sb_js.append("\t\t\tif(tabIframe.length==0){\n");
			sb_js.append("\t\t\t\tsrc = \"dragon/model/action/BizObjectHandler.ejw?\"+args[index];\n");
			sb_js.append("\t\t\t\ttab.html(\"<iframe scrolling='yes' frameborder='0' src='\"+src+\"' style='width: 100%; height: 100%;'></iframe>\");\n");
			sb_js.append("\t\t\t}\n\t\t}\n\t});\n");

			// 扩充的按钮
			sb_js.append("\t$('.panel-tool:first').prepend(\"<a href=\\\"javascript:void(0);\\\" class=\\\"panel-tool-a icon-reload\\\" title=\\\"刷新\\\" onclick=\\\"reloadAll()\\\"></a>\");\n");

			if (bizObject.getProcesses() != null) {
				for (BizProcess bp : bizObject.getProcesses()) {
					try {
						if (!PermissionCheck.checkProcessPermission(user, bizObject.getCode(), bp.getCode()) || !bp.getTarget().equalsIgnoreCase("tree"))
							continue;
					} catch (ExceptionHandler e) {
						e.printStackTrace();
					}

					sb_js.append("\t$(\".panel-tool:first\").prepend(\"<a href=\\\"javascript:void(0);\\\" class=\\\"panel-tool-a ").append(bp.getIconCls()).append("\\\"  title=\\\"").append(bp.getName()).append("\\\" onclick=\\\"");
					if (!StringUtils.isEmpty(bp.getUrl())) {
						hasOpenUrl = true;
						sb_js.append(" openUrl('").append(bp.getUrl()).append("',").append(bp.getMultiple() == 1 ? true : false).append(",").append(bp.getPopWindow() == 1 ? true : false).append(",'")
								.append(bp.getName()).append("',").append(bp.getPopWindowWidth()).append(",").append(bp.getPopWindowHeight()).append(",")
								.append(bp.getMaximizable() == 1 ? true : false).append(",").append(bp.getMaximize() == 1 ? true : false).append(");");
					} else if (!StringUtils.isEmpty(bp.getFunctionCall())) {
						sb_js.append(bp.getFunctionCall()).append("();");
					} else {
						sb_js.append(bp.getScript());
					}
					sb_js.append("\\\"</a>\");\n");

				}
			}

			sb_js.append("});\n");

			sb_js.append("function reloadAll() {\n\t$('#mytree').tree('reload', treeRoot.target);\n}\n");
			sb_js.append("function reloadSelected() {\n\tvar selected = $('#mytree').tree('getSelected');\n\tif(selected==null){\n\t\tselected = treeRoot;\n\t}\n\t$('#mytree').tree('reload', selected.target);\n}\n");
			sb_js.append("function refreshLeftTree(){\n\treloadSelected();\n}\n");
			sb_js.append("function load(node){\n");
			sb_js.append("\tvar arg;\n\tvar param;\n");
			for (int i = 0; i < bizObject.getDependby().size(); i++) {
				sb_js.append("\targ = args[" + i + "];\n");
				sb_js.append("\ttry{\n");
				sb_js.append("\t\tparam = node.attributes.").append(bizObject.getDependby().get(i).getDependParamV().toUpperCase()).append(";\n");
				sb_js.append("\t}catch(e){\n\t\tparam = 'null';\n\t}\n");
				sb_js.append("\targ = arg.substr(0,arg.lastIndexOf('=')+1)+param;\n");
				sb_js.append("\targs[" + i + "] = arg;\n");
			}

			sb_js.append("\tvar tabs = $('#tabs').tabs('tabs');\n\tfor(var i=0;i<tabs.length;i++){\n\t\tvar tab = tabs[i];tab.html('');\n\t}\n\t$('#tabs').tabs('select',0);\n}\n");

			if (hasOpenUrl) {
				sb_js.append("function openUrl(url,multiple,popWindow,title,popWindowWidth,popWindowHeight,maximizable,maximize){\n");
				sb_js.append("\tvar selected = $('#mytree').tree('getSelected');\n");
				sb_js.append("\tif(selected==null){\n\t\t selected = treeRoot;\n\t }\n");
				sb_js.append("\tif(popWindow){\n");
				sb_js.append("\t\tif(url.lastIndexOf('?')==url.length-1){\n\t\t\turl += '?root='+selected.id;\n\t\t}else{\n\t\t\turl += '&root=' + selected.id;\n\t\t}\n");
				sb_js.append("\t\ttop.showWindow('popWindow', title, url, popWindowWidth, popWindowHeight, maximizable, maximize);\n");
				sb_js.append("\t}else{\n");
				sb_js.append("\t\t$.post(url,{ root : selected.id },function(data){\n");
				sb_js.append("\t\t\tif(data.result != undefined && data.result == true){\n\t\t\t\ttop.showMsg(\"\", \"操作成功！\", false);\n\t\t\t}\n");
				sb_js.append("\t\t\tif(data.MESSAGE_ERROR != undefined && data.MESSAGE_ERROR != ''){\n\t\t\t\ttop.showMsg(\"错误\", data.MESSAGE_ERROR, true,'error');\n\t\t\t}else if(data.MESSAGE_WARNING != undefined && data.MESSAGE_WARNING != ''){\n\t\t\t\ttop.showMsg(\"警告\", data.MESSAGE_WARNING, true,'warning');\n\t\t\t}else if(data.MESSAGE_INFO != undefined && data.MESSAGE_INFO != ''){\n\t\t\t\ttop.showMsg(\"\", data.MESSAGE_INFO, false);\n\t\t\t}\n");
				sb_js.append("\t\t},'json');\n\t}\n}\n");
			}

			// js结束
			// html部分处理开始
			sb_html.append("<div class=\"easyui-layout\" data-options=\"fit:true\">\n\t<div data-options=\"region:'west',split:true\" title=\"树\" style=\"width: 200px;\">\n\t\t<ul id=\"mytree\"></ul>\n\t</div>\n");
			sb_html.append("\t<div data-options=\"region:'center',title:'列表'\" style=\"background: #fafafa; overflow: hidden\">\n\t\t<div id=\"tabs\" class=\"easyui-tabs\" fit=\"true\">\n");
			for (BizObject bo : bizObject.getDependby()) {
				sb_html.append("\t\t\t<div title=\"" + bo.getName() + "\" style=\"padding: 10px;\" id=\"slave_" + bo.getCode() + "\"></div>");
			}
			sb_html.append("\n\t\t</div>\n\t</div>\n</div>\n");

			// html部分处理结束

			js = sb_js.toString();
			html = sb_html.toString();

		} else {
			js = "$(function(){top.showMsg(\"\", \"未发现数据模型！\", false);});";
			html = "<font color=\"red\">未发现模型：</font>";
		}
		try {
			pageContext.setAttribute("js", js);
			pageContext.setAttribute("html", html);
		} catch (Exception e) {
			throw new JspException(e);
		}

		return EVAL_BODY_INCLUDE;
	}

	public String getJs() {
		return js;
	}

	public void setJs(String js) {
		this.js = js;
	}

	public String getHtml() {
		return html;
	}

	public void setHtml(String html) {
		this.html = html;
	}

}
